package nkr1pt.popkorn.download;

import com.google.inject.Inject;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.util.logging.Level;
import java.util.logging.Logger;
import nkr1pt.popkorn.download.DownloadCandidate.Host;
import nkr1pt.popkorn.exceptions.RecoverableException;
import nkr1pt.popkorn.helper.URLWrapper;
import nkr1pt.popkorn.properties.PropertyLoader;
import org.apache.commons.io.FilenameUtils;

/**
 *
 * @author Kristof Vanhaeren
 */
public class DownloadCandidateFactory {

    private CookieFactory cookieFactory;
    private PropertyLoader propertyLoader;
    private static final Logger logger = Logger.getLogger(DownloadCandidateFactory.class.getName());

    @Inject
    public DownloadCandidateFactory(CookieFactory cookieFactory, PropertyLoader propertyLoader) {
        this.cookieFactory = cookieFactory;
        this.propertyLoader = propertyLoader;
    }

    public DownloadCandidate createDownloadCandidate(File file) {
        DownloadCandidate candidate = new DownloadCandidate(file);

        if (file.length() == 0) {
            logger.log(Level.INFO, "Ignoring file {0} because it is empty", file.getName());
            candidate.setState(DownloadCandidateState.INVALID);
            return candidate;
        }

        try {
            String cookie = cookieFactory.getCookie(Host.RAPIDSHARE);
            candidate.setWaitingLocation(propertyLoader.getProperties().getDownloadCandidates());
            candidate.setInProgressLocation(propertyLoader.getProperties().getDownloadInProgress());
            candidate.setCompletedLocation(propertyLoader.getProperties().getDownloadCompleted());
            candidate.setFailedLocation(propertyLoader.getProperties().getDownloadFailed());
            candidate.setExtractionFailedLocation(propertyLoader.getProperties().getExtractionFailed());
            setCurrentLocation(candidate);
            createMetaInformation(candidate);
            FileReader fileReader = new FileReader(file);
            BufferedReader breader = new BufferedReader(fileReader);
            String line;
            while ((line = breader.readLine()) != null) {
                if (line.startsWith("http://")) {
                    DownloadCandidateItem downloadCandidateItem = new DownloadCandidateItem(candidate, new URLWrapper(new URL(line)));
                    downloadCandidateItem.setCookie(cookie);
                    candidate.addItem(downloadCandidateItem);
                } else if (line.startsWith("password:")) {
                    candidate.setArchivePassword(line.substring(10, line.length()));
                }
            }

            return candidate;
        } catch (RecoverableException e) {
            logger.info(e.getMessage());
            candidate.setState(DownloadCandidateState.INVALID);
            return candidate;
        } catch (IOException ioe) {
            logger.log(Level.SEVERE, ioe.getMessage());
            logger.log(Level.SEVERE, ioe.getStackTrace().toString());
        }

        return candidate;
    }

    private void setCurrentLocation(DownloadCandidate downloadCandidate) {
        File file = downloadCandidate.getFile();
        if (file.getAbsolutePath().contains(propertyLoader.getProperties().getDownloadCandidates())) {
            downloadCandidate.setCurrentLocation(propertyLoader.getProperties().getDownloadCandidates());
        } else if (file.getAbsolutePath().contains(propertyLoader.getProperties().getDownloadCompleted())) {
            downloadCandidate.setCurrentLocation(propertyLoader.getProperties().getDownloadCompleted());
        } else if (file.getAbsolutePath().contains(propertyLoader.getProperties().getDownloadFailed())) {
            downloadCandidate.setCurrentLocation(propertyLoader.getProperties().getDownloadFailed());
        } else if (file.getAbsolutePath().contains(propertyLoader.getProperties().getDownloadInProgress())) {
            downloadCandidate.setCurrentLocation(propertyLoader.getProperties().getDownloadInProgress());
        } else if (file.getAbsolutePath().contains(propertyLoader.getProperties().getExtractionFailed())) {
            downloadCandidate.setCurrentLocation(propertyLoader.getProperties().getExtractionFailed());
        }
    }

    private void createMetaInformation(DownloadCandidate candidate) {
        try {
            File metaInformation = new File(candidate.getCurrentLocation() + File.separator + "." + candidate.getName() + "_meta");
            metaInformation.createNewFile();
            candidate.setMetaInformation(metaInformation);
        } catch (IOException ex) {
            throw new RecoverableException("meta information file could not be created for " + candidate.getName());
        }
    }
}
